python 您所在的位置:网站首页 hive python python

python

#python| 来源: 网络整理| 查看: 265

python访问hive2

HiveServer2为客户端在远程执行hive查询提供了接口,通过Thrift RPC来实现,还提供了多用户并发和认证功能。目前使用python的用户可以通过pyhs2这个模块来连接HiveServer2,实现查询和取回结果的操作。

1.安装pyhs2 pip install pyhs2 yum install cyrus-sasl-plain yum install cyrus-sasl-devel

 yum install ython-devel.x86_64

  yum install cyrus-sasl-devel.x86_64

#如果有报错根据提示处理就行了,比较简单 2.实例展示

以下为一段小实例的代码,pyhs2提供了基本的功能,查询输出的结果为list,再将list的内容写入到exel里面,我要根据每个sql语句写入到对应的sheet中,设计到20多个,还有目前都是写入到了代码中,一些配置文件可以写到configparser配置文件中

#!/usr/bin/env python # -*- coding: utf-8 -*- # hive util with hive server2 """ @author:wyf @create:2016-06-29 16:55 """ __author__ = 'wyf' __version__ = '0.1' import pyhs2 import xlrd import xlwt import sys default_encoding = 'utf-8' if sys.getdefaultencoding() != default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) class HiveClient: def __init__(self, db_host, user, password, database, port=10000, authMechanism="PLAIN"): """ create connection to hive server2 """ self.conn = pyhs2.connect(host=db_host, port=port, authMechanism=authMechanism, user=user, password=password, database=database, ) def query(self, sql): """ query """ with self.conn.cursor() as cursor: cursor.execute(sql) return cursor.fetch() def close(self): """ close connection """ self.conn.close() def writeXlwt(filename,result): book=xlwt.Workbook() #打开一个工作薄 sheet1=book.add_sheet('sheel1')#添加一个sheet页 for i in range(len(result)+1): if i ==0: sheet1.row(i).write(0,'日期') sheet1.row(i).write(1,'小时') sheet1.row(i).write(2,'楼层') sheet1.row(i).write(3,'店铺号') sheet1.row(i).write(4,'店铺名称') sheet1.row(i).write(5,'人数') else: for a in range(len(result[i-1])): sheet1.row(i).write(a,result[i-1][a]) book.save(filename) def main(): """ main process """ try: hive_client = HiveClient(db_host='192.168.14.44', port=10000, user='hive', password='hive', database='test', authMechanism='PLAIN') sql = 'select * from test limit 10'#实例sql语句 result = hive_client.query(sql) hive_client.close() except pyhs2.error, tx: print '%s' % (tx.message) sys.exit(1) writeXlwt('test.xls',result) if __name__ == '__main__': main()


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有